from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from common.views.utils import table_api
from ..models.models import Dept

class DeptView(View):
    @method_decorator(login_required)
    def get(self, request):
        # 获取所有的顶级部门
        departments = Dept.objects.filter(parent_id=None)
        # 构造树状结构
        tree = []
        for department in departments:
            tree.append({
                'id': department.pk,
                'name': department.name,
                'code': department.code,
                'sort': department.sort,
                'spread': True,
                'remark':department.remark,
                'ca_time': department.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
                'up_time': department.up_time.strftime('%Y-%m-%d %H:%M:%S'),
                'children': DeptView.get_children(department)
            })

        # 返回 JSON 格式的数据
        return table_api(result=tree)

    @staticmethod
    def get_children(department):
        children = []
        sub_departments = Dept.objects.filter(parent_id=department.pk)
        if sub_departments:
            for sub_department in sub_departments:
                children.append({
                    'id': sub_department.pk,
                    'name': sub_department.name,
                    'code': sub_department.code,
                    'sort': sub_department.sort,
                    'spread': sub_department.enabled,
                    'remark': sub_department.remark,
                    'ca_time': sub_department.ca_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'up_time': sub_department.up_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'children': DeptView.get_children(sub_department)
                })
            return children
        else:
            return None